package com.greyshark.bledemo.tools

import android.Manifest
import android.os.Build
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils

object PermissionTools {

    private val TAG = PermissionTools::class.java.simpleName

    @RequiresApi(Build.VERSION_CODES.S)
    //蓝牙
    val PERMISSION_BLE12 = arrayOf(
        Manifest.permission.BLUETOOTH_SCAN,
        Manifest.permission.BLUETOOTH_CONNECT
    )

    //定位
    val PERMISSION_GROUP_LOCATION = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION
    )

    //文件存储
    val PERMISSION_STORAGE = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    fun checkPermissions(vararg permissions: String): Boolean {
        val result = PermissionUtils.isGranted(*permissions)
        LogUtils.d(
            TAG,
            "检测权限是否授权 - ${permissions.toList().toTypedArray().contentToString()}"
        )
        LogUtils.d(TAG, "是否授权 - $result")
        return result
    }

    fun requestPermissions(perName: String, permissions: Array<String>, block: () -> Unit) {
        PermissionUtils
            .permission(*permissions)
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(granted: MutableList<String>) {
                    LogUtils.d(TAG, "申请权限同意 - $granted")
                    if (checkPermissions(*permissions)) {
                        block()
                    }
                }

                override fun onDenied(
                    deniedForever: MutableList<String>,
                    denied: MutableList<String>
                ) {
                    LogUtils.d(TAG, "申请权限永远拒绝 - $deniedForever,\n拒绝 = $denied")
                }
            }
            ).request()
    }
}